<?php

// 参考：http://www.php.net/manual/zh/pdo.connections.php
// https://segmentfault.com/a/1190000004106175

include_once 'db_config.php';
try {
// array(PDO::ATTR_PERSISTENT => true) 开启持久化连接
    $dbh = new PDO('mysql:host=localhost;dbname=wx', $db['user'], $db['pwd'], array(PDO::ATTR_PERSISTENT => true));
// 获取指定日期的净增用户总量
//$sql = 'SELECT sum(new_user),sum(cancel_user),sum(net_user) FROM `usersummary` where ref_date = "2016-01-06"';

    $next_month = '2016-01';
// 获取初始年月到当前年月
    while (strtotime($next_month) < strtotime(date('Y-m'))) {
//    echo $next_month . '<br />';
        $sql = 'SELECT sum(new_user) as new_user,sum(cancel_user) as cancel_user,sum(net_user) as net_user FROM `usersummary` where ref_date like "' . $next_month . '%"';
        foreach ($dbh->query($sql) as $row) {
            // 把日期和用户数单独组成列 | 变量追加到数组中
            $arr['ref_date'][] = $next_month;
            $arr['new_user'][] = $row['new_user'];
            $arr['cancel_user'][] = -$row['cancel_user'];
            $arr['net_user'][] = $row['net_user'];
        }
//        $next_month_today = date("Y-m-d", strtotime("+1 months", strtotime('2016-01-06')));
        $next_month = date("Y-m", strtotime("+1 months", strtotime($next_month)));
    }
//$next_day = '2016-01-06';
//// 获取初始年月到当前年月日
//while (strtotime($next_day) <= strtotime(date('Y-m-d'))) {
//    echo $next_day.'<br />';
//    $next_day_today = date("Y-m-d",strtotime("+1 days",strtotime('2016-01-06')));
//    $next_day = date("Y-m-d",strtotime("+1 days",strtotime($next_day)));
//}
//echo date("Y-m-d",strtotime("+1 days",strtotime('2016-01-06'))).'<br />';
//// 获取指定日期的下一月
//echo date("Y-m",strtotime("+1 months",strtotime('2016-01-06'))).'<br />';
//// 获取指定日期的下一年
//echo date("Y",strtotime("+1 years",strtotime('2016-01-06'))).'<br />';
//// 把数据转换成json格式
    $data = json_encode($arr);
//file_put_contents('usersummary_'.date('Y-m-d').'.json', $data);
    echo $data;

// 现在运行完成，在此关闭连接
    $dbh = null;
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}
?>